﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Active.Core;
using System.Text;
using System.Globalization;
using Active.Core.State;

public partial class Bill_CustomerOrders : System.Web.UI.Page
{
    private enum Views
    {
        MainView = 0,
        EditCustomerOrderView = 1
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ApplyAuthorizationRules();
        }
    }

    private void ApplyAuthorizationRules()
    {
        Order obj = GetOrder();
        if (Order.CanAddObject())
        {
            
            if (obj.CustomerOrders.Count == 0)
            {
                this.MultiView1.ActiveViewIndex = (int)Views.EditCustomerOrderView;
                this.CustomerOrderDetailsView.DefaultMode = DetailsViewMode.Insert;
            }
        }
        this.lbtnAddCustomerOrder.Visible = CanEdit();
        CustomerOrdersGridView.Columns[0].Visible = obj.Media.Category != MediaType.Publication;
        CustomerOrdersGridView.Columns[CustomerOrdersGridView.Columns.Count - 1].Visible =
                CustomerOrdersGridView.Columns[CustomerOrdersGridView.Columns.Count - 2].Visible = CanEdit();
        txtDescription.Text = obj.CustomerDescription;
    }

    protected bool CanEdit()
    {
        Order obj = GetOrder();
        return Order.CanAddObject() && obj.StateValue == StateValue.CustomerEmployeeWorking;
    }

    protected void lbtnAddCustomerOrder_Click(object sender, EventArgs e)
    {
        this.MultiView1.ActiveViewIndex = (int)Views.EditCustomerOrderView;
        this.CustomerOrderDetailsView.DefaultMode = DetailsViewMode.Insert;
    }

    protected void btnSaveOrder_Click(object sender, EventArgs e)
    {
        Order obj = GetOrder();
        obj.CustomerDescription = txtDescription.Text;
        SaveOrder(obj);
    }

    #region Business Methods

    protected Order GetOrder()
    {
        string idString = Request.QueryString["id"];
        object businessObj = Session["CurrentObj"];
        if (businessObj == null || !(businessObj is Order)
            || (!IsPostBack && !((Order)businessObj).Id.ToString().Equals(idString)))
        {
            try
            {
                if (!string.IsNullOrEmpty(idString))
                {
                    businessObj = Order.GetOrder(int.Parse(idString));
                }
                else
                {
                    Response.Redirect("~/Bill");
                }
                Session["CurrentObj"] = businessObj;
            }
            catch (System.Security.SecurityException)
            {
                Response.Redirect("~/Bill");
            }
        }
        return businessObj as Order;
    }

    private CustomerOrder _custOrder;
    private CustomerOrder GetCustOrder()
    {
        
        return _custOrder;
    }

    private int SaveOrder(Order obj)
    {
        int rowsAffected = 0;
        try
        {
            Session["CurrentObj"] = obj.Save();
            rowsAffected = 1;
        }
        catch (Csla.Validation.ValidationException ex)
        {
            throw;
        }
        catch (Csla.DataPortalException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
        return rowsAffected;
    }

    #endregion

    #region CustomerOrdersDataSource

    protected void CustomerOrdersDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = GetOrder().CustomerOrders;
    }

    #endregion

    #region CustomerOrderDataSource

    protected void CustomerOrderDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = GetCustOrder();
    }

    protected void CustomerOrderDataSource_InsertObject(object sender, Csla.Web.InsertObjectArgs e)
    {
        Order order = GetOrder();
        CustomerOrder custOrder = order.CustomerOrders.AddNew();
        Caculate(custOrder, e.Values);
        e.RowsAffected = SaveOrder(order);
        Response.Redirect(Request.RawUrl, true);
    }

    protected void CustomerOrderDataSource_UpdateObject(object sender, Csla.Web.UpdateObjectArgs e)
    {
        Order order = GetOrder();
        CustomerOrder custOrder = order.CustomerOrders.GetCustomerOrderById((int)e.Keys["Id"]);
        Caculate(custOrder, e.Values);
        e.RowsAffected = SaveOrder(order);
        Response.Redirect(Request.RawUrl, true);
    }

    private void Caculate(CustomerOrder custOrder, IDictionary values)
    {
        values["Discount"] = values["Discount"].ToString().Replace("%", "");
        values["RealDiscount"] = values["RealDiscount"].ToString().Replace("%", "");
        Csla.Data.DataMapper.Map(values, custOrder);
        custOrder.Discount = custOrder.Discount / 100;
        custOrder.RealDiscount = custOrder.RealDiscount / 100;

        switch (custOrder.Category)
        {
            case OrderType.Additional:
                custOrder.Payout =
                    custOrder.RealPayout = custOrder.UnitPrice * custOrder.Times;
                custOrder.Times = 0;
                custOrder.Discount = 0;
                custOrder.RealDiscount = 0;
                break;
            case OrderType.Pay:
                custOrder.Payout = custOrder.UnitPrice * custOrder.Times * (decimal)(1 - custOrder.Discount);
                custOrder.RealPayout = 
                    custOrder.UnitPrice * custOrder.Times * (decimal)(1 - custOrder.RealDiscount);
                break;
            default:
                custOrder.Payout = 0;
                custOrder.RealPayout = 0;
                custOrder.Discount = 0;
                custOrder.RealDiscount = 0;
                break;
        }
    }

    #endregion

    #region CustomerOrderDetailView and it's child controls
    protected void CustomerOrderDetailsView_DataBound(object sender, EventArgs e)
    {
        Order order = GetOrder();
        if (order.Media.Category == MediaType.Publication)
        {
            this.CustomerOrderDetailsView.Rows[1].Visible = false;
        }
    }

    protected void CustomerOrderDetailsView_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        if (e.CommandName == "Cancel")
        {
            Response.Redirect(Request.RawUrl, true);
        }
    }

    #endregion

    #region CustomerOrdersGridView

    protected void CustomerOrdersGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            Order order = GetOrder();
            _custOrder = order.CustomerOrders.GetCustomerOrderById(int.Parse(e.CommandArgument.ToString()));
            this.CustomerOrderDetailsView.DefaultMode = DetailsViewMode.Edit;
            this.MultiView1.ActiveViewIndex = (int)Views.EditCustomerOrderView;
        }
        else if (e.CommandName == "Delete")
        {
            Order order = GetOrder();
            order.CustomerOrders.Remove(int.Parse(e.CommandArgument.ToString()));
            SaveOrder(order);
            Response.Redirect(Request.RawUrl, true);
        }
    }

    decimal _totalPayout = 0m;
    decimal _totalRealPayout = 0m;

    protected void CustomerOrdersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CustomerOrder customerOrder = e.Row.DataItem as CustomerOrder;
            _totalPayout += customerOrder.Payout;
            _totalRealPayout += customerOrder.RealPayout;
        }
        else if (e.Row.RowType == DataControlRowType.Footer)
        {
            Order obj = GetOrder();
            e.Row.Cells[1].Text = "合计：";
            e.Row.Cells[2].Text = obj.Times.ToString();
            e.Row.Cells[4].Text = _totalPayout.ToString("f2");
            e.Row.Cells[4].CssClass = "right";
            e.Row.Cells[6].Text = _totalRealPayout.ToString("f2");
            e.Row.Cells[6].CssClass = "right";
        }
    }

    #endregion

    
}
